package com.jm.service;

import com.jm.mapper.AccountMapper;
import com.jm.model.Account;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@Service(version = "1.0.0")
@Slf4j
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void decAccount(Account account) {
        log.info("全局事务id ：" + RootContext.getXID());
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("user_id", account.getUserId());
        Account accountDB = accountMapper.selectByMap(paramsMap).get(0);
        if (accountDB.getAmount().compareTo(account.getAmount()) < 0) {
            throw new RuntimeException("账户余额不足");
        }
        int count = accountMapper.decAccount(account.getUserId(), account.getAmount(), accountDB.getAmount());
        if (count <= 0) {
            throw new RuntimeException("扣减账号失败");
        }
    }
}
